<template>
  <div v-if="!item.meta?.hidden">
    <!-- 有子菜单 -->
    <el-sub-menu
      v-if="hasChildren"
      :index="resolvedIndex"
    >
      <template #title>
        <el-icon v-if="item.meta?.icon">
          <component :is="item.meta.icon" />
        </el-icon>
        <span>{{ item.meta?.title }}</span>
      </template>

      <SidebarItem
        v-for="child in item.children"
        :key="child.path"
        :item="child"
        :base-path="resolvePath(item.path)"
      />
    </el-sub-menu>

    <!-- 无子菜单 -->
    <el-menu-item v-else :index="resolvedIndex">
      <el-icon v-if="item.meta?.icon">
        <component :is="item.meta.icon" />
      </el-icon>
      <span>{{ item.meta?.title }}</span>
    </el-menu-item>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  item: { type: Object, required: true },
  basePath: { type: String, default: '' }
})

const isExternal = (path) => /^(https?:|mailto:|tel:)/.test(path)

const joinPath = (...segs) => {
  const cleaned = segs
    .filter(Boolean)
    .map(s => String(s).replace(/\/+/g, '/'))
  const joined = cleaned.join('/').replace(/\/+/g, '/')
  return joined.startsWith('/') ? joined : '/' + joined
}

// 解析为绝对 index
const resolvePath = (routePath) => {
  if (isExternal(routePath)) return routePath
  if (routePath.startsWith('/')) return routePath
  return joinPath(props.basePath, routePath)
}

const hasChildren = computed(() =>
  Array.isArray(props.item.children) && props.item.children.length > 0
)

const resolvedIndex = computed(() => resolvePath(props.item.path))
</script>